<?php

class socketAuth
{
    /** @const int 认证token超时时间 */
    const TOKEN_TIMEOUT = 600;
    const SALT = '1cc16f803dc544859c797a87ba58756c';
    const PREFIX = 'SocketAuth';
    const SPLIT = '.';

    protected mixed $userId;

    private int $currentTime;

    public function __construct($userId = null)
    {
        $this->userId = $userId;
        $this->currentTime = time();
    }

    public function createToken(): string
    {
        $split = self::SPLIT;
        return sprintf(
          '%s%s%s%s%s',
          $this->userId,
          $split,
          $this->currentTime,
          $split,
          $this->getSign($this->userId, $this->currentTime)
        );
    }

    public function validateToken($token)
    {
        list($userId, $time, $token) = explode(self::SPLIT, $token);
        if ($token != $this->getSign($userId, $time)) {
            throw new \Exception('token无效');
        }
        if ($this->currentTime - $time > self::TOKEN_TIMEOUT) {
            throw new \Exception('token已失效');
        }
        return $userId;
    }

    private function getSign($userId, $time): string
    {
        $split = self::SPLIT;
        return md5(sprintf('%s%s%s%s%s', $userId, $split, $time, $split, self::SALT));
    }
}